package bman.filecopy;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FCC implements MessageReceiver
{
	FileSysRemote fs;
	MessageReceiver mr;
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception
	{
		Logger log = Logger.getLogger("");
		log.setLevel(Level.OFF);
		FCC f = new FCC(null);
		f.run();
	}
	
	public FCC(MessageReceiver r)
	{
		if(r == null)
		{
			mr = this;
		}
		else
		{
			mr = r;
		}
	}
	
	private void run() throws Exception
	{
		display("Stated File Copy client version 1.0 \n");
		
		boolean run = true;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		while(run)
		{
			String cmd = br.readLine();
			processCommand(cmd);
		}
	}
	
	public void processCommand(String cmd) 
	{
		if("exit".equals(cmd))
		{
			display("\nGood bye!!!");
			System.exit(0);
		}
		if(cmd.startsWith("connect"))
		{
			String address = cmd.substring(8).trim();
			if(fs == null)
			{
				fs = new FileSysRemote(address,mr);
			}
			else
			{
				fs.address = address;
			}
			
			try
			{
				boolean connect = fs.send("test token");
				display("connected to "+address);
			}
			catch(Exception ex)
			{
				display("connected: "+false+"\n" +
						"\n" +
						"Error is: "+ex);
			}
		}
		else if(fs == null)
		{
			display("\nYou are not connected. Connect first. \nThe command is: connect <ip:port>\n\n");
		}
		else
		{
			fs.send(cmd);
		}
	}
	
	private void display(String s)
	{
		mr.receive(s);
	}
	
	public void receive(String message)
	{
		System.out.print(message+"\n");
		System.out.print(":");
	}

}
